<template>
  <view class="content">
    <view class="content" :class="{'content-inner-layout':redirectBack}">
      <view class="hor-layout-center">
        <view>使用外部接口</view>
        <van-switch v-model="useOutApi" size="medium" style="margin-left: 10px"></van-switch>
      </view>
      <!--  1.电子签名  -->
      <view class="card-layout">
        <view>电子签名流程：</view>
        <view v-for="(item,index) in stepList" :key="index" class="hint-view">
          {{ item }}
        </view>
      </view>
      <button :disabled="businessId.length>0" size="mini" type="primary" style="margin-top: 10px;"
              @click="downloadPdfSign">1.下载Pdf文件-去电子签名
      </button>
      <!--  2.签名完成，签名结果  -->
      <view style="width: 90%;padding: 10px">businessId：
        <input class="value-text" v-model="businessId">
      </view>
      <button size="mini" @click="copyValue">复制businessId</button>

      <button :disabled="businessId.length<=0" size="mini" type="primary" style="margin-top: 10px;"
              @click="querySignInfoCloud">2.签署信息查询
      </button>
      <view class="box-layout">
        <view style="font-size: medium">签署完成，签署结果查询：</view>
        <view>签署时间：{{ signResult.signTime }}</view>
        <view>
          签署状态：{{ signResult.status }}
          <text v-if="signResult.status == 1">：盖了章</text>
          <text v-if="signResult.status == 2">：没盖章</text>
        </view>
        <view>签署文件列表:</view>
        <view class="sign-list" v-for="(item,index) in signResult.fileList" :key="index">
          <view>fileName:{{ item.fileName }}</view>
          <view>signFileId:{{ item.signFileId }}</view>
          <view>fileId:{{ item.fileId }}</view>
        </view>
      </view>

      <button size="mini" type="primary" style="margin-top: 10px;" :disabled="!canDownloadUse"
              @click="downloadSignPdf(false)">
        3.签署文件下载-预览
      </button>
      <button size="mini" type="success" style="margin-top: 10px" @click="downloadSignPdf(true)">
        下载签名的pdf文件测试
      </button>
    </view>
    <button size="mini" type="warn" style="margin-top: 10px" :disabled="!redirectBack" @click="closeWebviewWindow">
      返回
    </button>
  </view>
</template>

<script>
import axios from "axios";
import {fileStamp, params, sealBean} from "../index/params";
import _axios from "../../plugin/axios";
import "../../static/openjsbridge.icity.js"

export default {
  name: "sign",
  data() {
    return {
      useOutApi: false,
      // pdfUrl: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-67dcfd0c-c143-49dd-81a6-3d6aabd6ef7b/fcd05508-a510-446c-9ef5-85f8ec929bb4.pdf',
      // pdfKeyword: '签 名：',
      pdfUrl: 'https://mp-67dcfd0c-c143-49dd-81a6-3d6aabd6ef7b.cdn.bspapp.com/f1700705732490.pdf',
      pdfKeyword: '公章',
      signFile: {
        "title": "公司简介",
        "fileB64": "",
        "fileType": "PDF",
        "fileDesc": "公司简介"
      },
      sealBean,
      fileStamp,
      params,
      stepList: [],
      redirectBack: false,
      HlwyyToken: "48d8c2ffb80a466d93ed836aca987629",
      redirectUrl: 'https://static-67dcfd0c-c143-49dd-81a6-3d6aabd6ef7b.bspapp.com/msb/#/pages/login/sign',
      businessId: "",
      signResult: {signTime: '', status: undefined, fileList: []},
    }
  },
  computed: {
    canDownloadUse() {
      // return this.signResult.fileList.length ? true : false
      let signFileIdObj = this.signResult.fileList
      return this.businessId.length > 0 && signFileIdObj.length > 0 && signFileIdObj[0].signFileId
    }
  },
  onLoad(options) {
    // businessId=d9be29b2b1144ea1a7e7a04ea9f421cf
    console.log("onLoad", options)
    if (options.businessId) {
      this.redirectBack = true
      this.businessId = options.businessId
      uni.showLoading()
      // this.querySignInfoCloud()
      setTimeout(() => {
        uni.hideLoading()
        this.closeWebviewWindow()
      }, 500)
    }
  },
  onShow() {
    console.log("sign-onShow", process.env.NODE_ENV)
    // if (window.localStorage.getItem("businessId")) {
    //   this.businessId = window.localStorage.getItem("businessId")
    // }
  },
  methods: {
    closeWebviewWindow() {
      console.log("closeWebviewWindow")
      iCityBridge.closeWebView();
    },
    copyValue() {
      uni.setClipboardData({data: this.businessId, success: uni.showToast({title: '复制成功'})});
    },
    downloadPdfSign() {//这个pdf接口是https的不需要转换
      this.stepList = []
      this.stepList.push("第一步：下载后台接口返回的网络Pdf，得到blob文件流")
      axios({
        method: 'get',
        responseType: 'blob',
        url: this.pdfUrl,
      }).then(blob => {
        console.log("data====", blob)
        let oFileReader = new FileReader();
        oFileReader.onloadend = e => {
          this.stepList.push("第二步：下载Pdf完成，通过blob流得到base64字符串")
          // console.log("下载Pdf成功！", e.target.result)
          let result = e.target.result.replace("data:application/pdf;base64,", "");
          result = result.replace("data:text/plain;base64,", "");
          this.signFile.fileB64 = result
          this.toSignPdf()
        };
        oFileReader.readAsDataURL(blob.data);
      });
    },
    toSignPdf() {
      console.log("para", params)
      let outUrl = 'http://219.159.12.110:13001/h5sign/personal/signStart'
      let mUrl = 'http://msbyy.impc.com.cn/msb/hlwyy/business-ggfw/dzqz/grbd'
      this.stepList.push("第三步：将pdf的base64字符串及其他参数请求h5sign/personal/signStart个人签名接口获取签名路径")
      this.fileStamp.fileList = [this.signFile]
      this.sealBean.ruleInfo.keyWordRule.keyword = this.pdfKeyword
      this.fileStamp.sealList = [this.sealBean]
      this.params.fileStampList = [this.fileStamp]
      //todo 这里使用businessId作为回调页面的参数实际是有问题的，因为真正的businessId是这个接口下面生成的。并不是这里的入参。
      //todo 1.当前的处理方式是，在回调页面直接关闭webview的弹窗，就直接返回了之前的页面。
      //todo 2.如果需要在回调页面加载一些内容需要：在获取到businessId后通过手机号+时间戳作为key-businessId作为value保存到数据库，
      //todo 将key作为参数传到回调参数里面，返回回调页面再通过key值获取businessId进行相关业务查询。
      this.params.configInfo.redirectUrl = this.redirectUrl + '?businessId=' + this.businessId
      _axios({
        method: 'post',
        headers: {'Content-Type': 'application/json', 'Hlwyy-Token': this.HlwyyToken},
        body: JSON.stringify(this.params),
        url: this.useOutApi ? outUrl : mUrl,
      }).then(res => {
        console.log("toSignPdf=res============", res)
        let result = ''
        if (this.useOutApi) result = res.data
        else result = result = res.data.data
        console.log("toSignPdf=res============", result)
        if (!result || !result.data) {
          this.stepList.push(`第四步：获取签名接口调用失败！`)
          return
        }
        if (!this.useOutApi) result = JSON.parse(result.data)
        let {businessId, url} = result.data
        console.log("获取签名接口调用成功res==", url)
        this.stepList.push(`第四步：获取签名接口调用成功！`)
        this.stepList.push(`businessId=>>${businessId}`)
        this.stepList.push(`url=>>${url}`)
        this.stepList.push(`第五步：跳转到个人签名地址！`)
        this.businessId = businessId
        // window.localStorage.setItem("businessId", businessId)
        if (process.env.NODE_ENV != 'development')
          setTimeout(() => {
            iCityBridge.openWebView({
              title: '电子签章页面', //标题
              url: url,//页面地址
              isShowTopTitle: 0 //0:隐藏标题栏，1:显示标题栏
            });
          }, 3000)
      }).catch(err => {
        console.error("toSignPdf", err)
      })
    },
    // querySignInfo() {
    //   axios({
    //     method: 'get',
    //     params: {appId: 'APP_4E4E0490D21C44C7A439F847A7744D29'},
    //     url: `http://219.159.12.110:13001/h5sign/${this.businessId}`,
    //   }).then(res => {
    //     let result = res.data
    //     this.signResult = result.data
    //   }).catch(err => {
    //     console.error("querySignInfo", err)
    //   })
    // },
    querySignInfoCloud() {//2.调用云函数的url化接口获取数据
      let outUrl = `http://219.159.12.110:13001/h5sign/${this.businessId}`
      let mUrl = `http://msbyy.impc.com.cn/msb/hlwyy/business-ggfw/dzqz/xxcx`
      _axios({
        method: 'get',
        params: {appId: 'APP_4E4E0490D21C44C7A439F847A7744D29', businessId: this.businessId},
        headers: {'Hlwyy-Token': this.HlwyyToken},
        url: this.useOutApi ? outUrl : mUrl,
      }).then(res => {
        console.log("querySignInfoCloud", res)
        let result = ''
        if (this.useOutApi) {
          result = res.data
        } else {
          if (!res.data.data) {
            uni.showToast({title: "404请重试！"})
            return
          }
          result = JSON.parse(res.data.data.data)
          console.log("querySignInfoCloud", result)
          result = JSON.parse(result.data)
        }
        this.signResult = result.data
      }).catch(err => {
        console.error("querySignInfoCloud", err)
      })
    },
    downloadSignPdf(test) {
      let signFileId = '', url;
      if (test) {
        url = `https://mp-67dcfd0c-c143-49dd-81a6-3d6aabd6ef7b.cdn.bspapp.com/cloudstorage/test.pdf`
      } else {
        let signFileIdObj = this.signResult.fileList[0]
        signFileId = signFileIdObj.signFileId
        url = `http://219.159.12.110:13001/h5sign/downloadFiles/${this.businessId}?appId=APP_4E4E0490D21C44C7A439F847A7744D29&signFileId=${signFileId}`
        if (!this.useOutApi) {
          this.downloadSignPdfMsb()
          return
        }
      }
      this.downloadPdf(url)
      return;
      axios({
        url: url, method: 'get', responseType: 'blob',
        params: {appId: 'APP_4E4E0490D21C44C7A439F847A7744D29', signFileId},
      }).then(res => {
        console.log("downloadSignPdf", res, res.data)
        const blob = res.data
        const e = new Blob([blob], {type: 'application/pdf'})
        let url = URL.createObjectURL(e);
        // this.downloadPdfPreview(url)
        // this.downloadPdfHref(url)
        this.downloadPdf(url)
        this.previewPdf(url)
      })
    },
    downloadSignPdfMsb() {
      let url = "http://msbyy.impc.com.cn/msb/hlwyy/business-ggfw/dzqz/wjxz"
      let signFileIdObj = this.signResult.fileList[0]
      let signFileId = signFileIdObj.signFileId
      _axios({
        method: 'get',
        params: {appId: 'APP_4E4E0490D21C44C7A439F847A7744D29', businessId: this.businessId, signFileId},
        headers: {'Hlwyy-Token': this.HlwyyToken},
        url: url,
      }).then(res => {
        console.log("downloadSignPdfMsb", res)
        let result = res.data
        if (!result.data) {
          uni.showToast({title: "404请重试！"})
          return
        }
        let {fileFullPath} = result.data
        let downloadUrl = `http://mdej.impc.com.cn/hlwyy/business-ggfw/fileFeign/downloadFile?fileFullPath=${fileFullPath}`
        this.downloadPdf(downloadUrl)
        this.previewPdf(downloadUrl)
      }).catch(err => {
        console.error("downloadSignPdfMsb", err)
      })
    },
    downloadPdf(url) {
      let link = document.createElement('a') //创建a标签
      link.style.display = 'none'  //将a标签隐藏
      link.href = url  //给a标签添加下载链接
      link.setAttribute('download', '蒙速办') // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
      document.body.appendChild(link)
      link.click()  //执行
    },
    previewPdf(url) {
      uni.navigateTo({
        url: '/pages/index/webview?title=pdf预览&pdfUrl=' + encodeURIComponent(url)
      })
    },
    showToast(title) {
      uni.showToast({title})
    },
  }
}
</script>

<style scoped>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.content-inner-layout {
  opacity: 0.2;
}

.card-layout {
  display: flex;
  flex-direction: column;
  margin: 10px;
  background: #eaeaea;
  border-radius: 5px;
  padding: 4px;
}

.hint-view {
  word-break: break-all;
  font-size: smaller;
  color: orangered;
}

.box-layout {
  font-size: small;
  background: lavenderblush;
  border-radius: 5px;
  padding: 10px;
  margin: 10px;
}

.sign-list {
  background: lightslategray;
  border-radius: 5px;
  padding: 10px;
  margin: 10px;
}

.value-text {
  padding: 5px 8px;
  border: 1px solid #eaeaea;
  word-break: break-all;
}

.hor-layout-center {
  display: flex;
  flex-direction: row;
  align-items: center;
  background: #95dea2;
  padding: 10px 40px;
  border-radius: 10px;
}
</style>
